require File.expand_path(File.dirname(__FILE__) + '/desktop_updater')
require File.expand_path(File.dirname(__FILE__) + '/util')
require File.expand_path(File.dirname(__FILE__) + '/../config')

class Installer
  def install_latest_idea force
    install_idea(find_latest_distr, force)
  end

  def install_latest_idea_dev force
    install_idea_dev(find_latest_dev_distr, force)    
  end

  private 
  
  def install_idea filepath, force = false
    filename = File.basename(filepath)
    dest_dir = INSTALLATION_PATH + "/" + distr_to_dir_name(filename)
    if File.exists? dest_dir then
      puts "the latest downloaded version (#{filename}) seems to be already installed"
      return unless force
      puts "install is forced"
      `rm -rf #{dest_dir}`
    end

    begin
      Dir.chdir(INSTALLATION_PATH) do
        notify_of("untarring '#{filename}'") { `tar zxfv #{filepath}` }
      end
      notify_of("copying config") { `cp -r #{IDEA_CONFIG}/* #{dest_dir}/bin` } if defined?(IDEA_CONFIG)
    end

    DesktopUpdater.new.do_update([:dest_dir => dest_dir])
  
    puts "installation finished"
  end

  def install_idea_dev filepath, force = false
    filename = File.basename(filepath)

    idea_dest_dir = "#{INSTALLATION_PATH}/#{filename[0..3]}-#{filename[4..7]}/"
    if not File.exists?(idea_dest_dir) then
      puts "couldn't find folder #{idea_dest_dir}"
      puts "it seems there is no IntelliJ installation for latest version of development kit"
      puts "IntelliJ should be installed before installing devkit"
      return
    end

    dest_dir = "#{idea_dest_dir}/#{distr_to_dev_dir_name(filename)}"
    if File.exists? dest_dir then
      puts "the latest downloaded version (#{filename}) seems to be already installed"
      return unless force
      puts "install is forced"
      `rm -rf #{dest_dir}`
    end

    notify_of("unzipping #{filename}") {`unzip #{filepath} -d #{dest_dir}`}
    puts "dev pack installation finished"
  end

  def find_latest_distr
    Dir.glob("#{DOWNLOAD_PATH}/idea*.tar.gz").sort_by { |f| File.new(f).mtime }.last
  end

  def find_latest_dev_distr
    Dir.glob("#{DOWNLOAD_PATH}/idea*dev.zip").sort_by { |f| File.new(f).mtime }.last
  end

  def distr_to_dir_name filename
    "#{filename[0..3]}-#{filename[4..-8]}"
  end

  def distr_to_dev_dir_name filename
    filename.sub(".zip", "")
  end
end
  